<?php
namespace Lib;
/**
 * Class Logs
  */
class Logs {
    const TYPE_EMERG  = 'EMERG';
    const TYPE_FATAL  = 'FATAL';
    const TYPE_ALERT  = 'ALERT';
    const TYPE_CRIT   = 'CRIT';
    const TYPE_ERROR  = 'ERROR';
    const TYPE_WARN   = 'WARN';
    const TYPE_NOTICE = 'NOTICE';
    const TYPE_INFO   = 'INFO';
    const TYPE_DEBUG  = 'DEBUG';

    // 日志文件存储目录
    /**
     * @var string
     */
    protected static $_LogPath = '';

    /**
     * 单个日志文件大小限制
     *
     * @var int 字节数
     */
    private static $i_log_size = 5242880; // 1024 * 1024 * 5 = 5M

    /**
     * 设置单个日志文件大小限制
     * @param $i_size
     */
    public static function setSize($i_size) {
        if( is_numeric($i_size) ){
            self::$i_log_size = $i_size;
        }
    }

    /**
     * 设置日志存储目录
     * @param $LogPath
     * @return mixed
     */
    public static function setLogPath($LogPath) {
        if (!file_exists($LogPath) ) {
            mkdir($LogPath,0777,true) or exit('mkdir '.$LogPath.' error');
        }else{
            //chmod($LogPath,0700);
        }
        is_writable($LogPath) or exit("log_path ($LogPath) is not writeable !");
        self::$_LogPath = $LogPath;
        return self::$_LogPath = realpath($LogPath);
    }

    /**
     * 获取日志存储目录
     * @return bool|string
     */
    public static function getLogPath() {
         if (empty(self::$_LogPath)){//如果未指定日志目录，设置为“../logs”
             //self::$_LogPath = self::setLogPath(Config::getRootPath().DIRECTORY_SEPARATOR.'logs');
             self::setLogPath(Config::ini('LOGPATH',Config::getRootPath()).DIRECTORY_SEPARATOR.'logs');
         }
        // 检查日志目录是否可写
        return self::$_LogPath;
    }

    /**
     * 写日志
     * @param $s_message
     * @param string $type
     * @return bool
     */
    private static function write($s_message, $type = 'LOG') {
        $log_path = self::getLogPath();
        $s_now_time = date('[Y-m-d H:i:s]');
        $s_now_day  = date('Y_m_d');
        // 根据类型设置日志目标位置
        $s_target = $log_path .DIRECTORY_SEPARATOR. $type . '_' . $s_now_day . '.log';

        //检测日志文件大小, 超过配置大小则重命名
        if (file_exists($s_target) and self::$i_log_size <= filesize($s_target)) {
            $s_file_name = substr(basename($s_target), 0, strrpos(basename($s_target), '.log')) . '_' . time() . '.log';
            rename($s_target, dirname($s_target) . DIRECTORY_SEPARATOR . $s_file_name);
        }
        clearstatcache();//清除文件状态缓存
        // 写日志, 返回成功与否
        return error_log("$s_now_time $s_message\n", 3, $s_target);
    }


    /**
     * @param $msg
     */
    public static function Debug($msg) {
        self::write($msg,self::TYPE_DEBUG);
    }

    /**
     * @param $msg
     */
    public static function Error($msg) {
        self::write($msg,self::TYPE_ERROR);
    }

    /**
     * @param $msg
     */
    public static function Notice($msg) {
        self::write($msg,self::TYPE_NOTICE);
    }
}